package com.example.cloud.controller.scoket;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.cloud.model.dto.Result;
import com.example.cloud.model.system.Account;
import com.example.cloud.model.system.Organ;
import com.example.cloud.model.system.User;
import com.example.cloud.pojo.Friend;
import com.example.cloud.pojo.Group;
import com.example.cloud.pojo.Mine;
import com.example.cloud.service.system.AccountService;
import com.example.cloud.service.system.UserService;
import com.example.cloud.socket.WebSocketServer;
import com.example.cloud.utils.RequestUtil;
import com.example.cloud.utils.ResultUtil;
import com.example.cloud.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.websocket.EncodeException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created by wangtao on 2018/5/22.
 */
@RestController
@RequestMapping("/socket")
public class SocketController {

    private Logger logger = LoggerFactory.getLogger(SocketController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private AccountService accountService;

    @GetMapping("/getOnline/{id}")
    public Result getOnline(@PathVariable Long id){
        String status = "offline";
        if(WebSocketServer.clientMaps.containsKey(id)){
            status = "online";
        }
        return ResultUtil.success(status, null);
    }

    @PostMapping("/send")
    public void send(@RequestBody Map map) throws IOException, EncodeException {
        Long clientId = Long.valueOf(map.get("clientId").toString());
        if(WebSocketServer.clientMaps.containsKey(clientId)){
            JSONObject json = new JSONObject();
            json.put("emit", "reload");
            WebSocketServer.clientMaps.get(clientId).sendMessage(JSON.toJSONString(json));
        }
    }

    @GetMapping("/init/{id}")
    public Result init(@PathVariable Long id){
        User loginUser = RequestUtil.getLoginUser();
        JSONObject json = new JSONObject();
        // 加载个人主信息
        Mine mine = new Mine();
        mine.setId(loginUser.getId());
        mine.setUsername(loginUser.getUsername());
        Map<Long, WebSocketServer> clientMaps = WebSocketServer.clientMaps;
        mine.setStatus("online");
        if(StringUtils.isNotBlank(loginUser.getSign())){
            mine.setSign(loginUser.getSign());
        }else{
            mine.setSign("该用户很懒，什么都没写~");
        }
        if(StringUtils.isNotBlank(loginUser.getAvatar())){
            mine.setAvatar(loginUser.getAvatar());
        }else{
            mine.setAvatar("http://img.mp.sohu.com/upload/20170517/8980a5d2d380470789e0e558a1edaf32.png");
        }
        // 加载站内好友
        List<User> users = userService.findByAll();
        List<Friend> friends = new ArrayList<>();
        Map<Long, List<User>> collect = users.stream().collect(Collectors.groupingBy(User::getAccountId));
        for (Map.Entry<Long, List<User>> entry : collect.entrySet()) {
            Account account = accountService.findOneFromCache(entry.getKey());
            if(account != null){
                Friend friend = new Friend();
                friend.setId(account.getId());
                friend.setGroupname(account.getAccountName());
                List<Mine> list = new ArrayList<>();
                for (User user : entry.getValue()) {
                    Mine m = new Mine();
                    m.setId(user.getId());
                    m.setUsername(user.getUsername());
                    if(clientMaps.containsKey(user.getId())){
                        m.setStatus("online");
                    }else{
                        m.setStatus("offline");
                    }
                    if(StringUtils.isNotBlank(user.getSign())){
                        m.setSign(user.getSign());
                    }else{
                        m.setSign("该用户很懒，什么都没写~");
                    }
                    if(StringUtils.isNotBlank(user.getAvatar())){
                        m.setAvatar(user.getAvatar());
                    }else{
                        m.setAvatar("http://img.mp.sohu.com/upload/20170517/8980a5d2d380470789e0e558a1edaf32.png");
                    }
                    list.add(m);
                }
                friend.setList(list);
                friends.add(friend);
            }
        }
        // 加载群组
        List<Group> groups = new ArrayList<>();
        List<Organ> organs = loginUser.getOrgans();
        for (Organ organ : organs) {
            if(organ.getParentId() != null){
                Group group = new Group();
                group.setId(organ.getId());
                group.setGroupname(organ.getOrganName());
                if(StringUtils.isNotBlank(organ.getAvatar())){
                    group.setAvatar(organ.getAvatar());
                }else{
                    group.setAvatar("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1543486777973&di=22b7d79f93851157140aeaafe91737e9&imgtype=0&src=http%3A%2F%2Fhiphotos.baidu.com%2Ffeed%2Fpic%2Fitem%2F0823dd54564e92582f5d29039082d158cdbf4ef6.jpg");
                }
                groups.add(group);
            }
        }
        json.put("mine", mine);
        json.put("friend", friends);
        json.put("group", groups);
        return ResultUtil.success(json);
    }

    @GetMapping("/getMembers")
    public Result getMembers(@RequestParam("id") Long id){
        JSONObject result = new JSONObject();
        JSONArray list = new JSONArray();
        List<User> users = userService.findByOrganIdFromCache(id);
        for (User user : users) {
            List<Long> ids = new ArrayList<>();
            for (Organ organ : user.getOrgans()) {
                ids.add(organ.getId());
            }
            if(ids.contains(id)){
                JSONObject data = new JSONObject();
                data.put("id", user.getId());
                data.put("username", user.getUsername());
                if(StringUtils.isNotBlank(user.getAvatar())){
                    data.put("avatar", user.getAvatar());
                }else{
                    data.put("avatar", "http://img.mp.sohu.com/upload/20170517/8980a5d2d380470789e0e558a1edaf32.png");
                }
                data.put("sign", user.getSign());
                list.add(data);
            }
        }
        result.put("list", list);
        return ResultUtil.success(result);
    }
}
